package pl.edu.agh.inpema.components.receivers.phpBB2Receiver.connector;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpConnectionManager;
import org.apache.commons.httpclient.SimpleHttpConnectionManager;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.htmlparser.lexer.Page;


public class ForumConnector {
	
	private String baseAddress;

	private HttpClient httpClient;
	
	private String charset = Page.DEFAULT_CHARSET;
	
	private long sleepTime;
	
	public ForumConnector(String baseAddress, long sleepTime) {
		this.baseAddress = baseAddress;
		
		this.sleepTime = sleepTime;
		
		HttpConnectionManager connectionManager = new SimpleHttpConnectionManager();
		httpClient = new HttpClient(connectionManager);
		
		httpClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
		httpClient.getParams().setParameter("http.protocol.single-cookie-header", new Boolean(true));
	}
	
	
	public void setCharset(String charset) {
		this.charset = charset;
	}
	
	public void performLogin(String login, String password) throws ConnectionException {
		PostMethod pmethod = new PostMethod(this.baseAddress+"login.php");
		pmethod.setParameter("login", "Zaloguj");
		pmethod.setParameter("username", login);
		pmethod.setParameter("password", password);
		
		try {
			int statusCode = httpClient.executeMethod(pmethod);
		} catch (IOException e) {
			throw new ConnectionException("IOException: " + e.getMessage());
		} finally {
			pmethod.releaseConnection();
		}
	}
	
	public String getMainPage() throws ConnectionException {
		return this.getPage("");
	}
	
	public String getPage(String address) throws ConnectionException {
		//System.out.println("--"+this.baseAddress + address+"--");
		GetMethod gmethod = new GetMethod(this.baseAddress + address);
		String response = null;
		try {
			int statusCode = httpClient.executeMethod(gmethod);
			if (statusCode != HttpURLConnection.HTTP_OK) {
				throw new ConnectionException("Wrong response code: "+statusCode);
			}
			InputStream responseStream = gmethod.getResponseBodyAsStream();
			//byte[] byteBody = gmethod.getResponseBody();
			//response = new String(byteBody, this.charset);
			response = this.convertStreamToString(responseStream);
			
			//response = gmethod.getResponseBodyAsString();
		} catch (IOException e) {
			throw new ConnectionException("IOException: " + e.getMessage());
		} finally {
			gmethod.releaseConnection();
		}
		if (this.sleepTime > 0) {
			try {
				Thread.sleep(this.sleepTime);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		return response;
	}
	
	 private String convertStreamToString(InputStream is) {
		 StringBuilder sb = new StringBuilder();
		 try {
			 BufferedReader reader = new BufferedReader(new InputStreamReader(is, this.charset));
			 String line = null;
			 while ((line = reader.readLine()) != null) {
				 sb.append(line + "\n");
			 }
		 } catch (IOException e) {
			 e.printStackTrace();
		 } finally {
			 try {
				 is.close();
			 } catch (IOException e) {
				 e.printStackTrace();
			 }
		 }
		 return sb.toString();
	 }

}
